# -*- coding: utf-8 -*-
from .models import DevType, DevEname, Device
from django.shortcuts import render
from utils.cryption import Cryption
from utils.decorators import service_required
from utils.viewutil import get_user, ajaxresponse, pages, savelog


@service_required('sys_config')
def list_devtype(request):
    """设备类型列表"""
    devs = DevType.objects.all()
    s, e, pagination = pages(request, devs)
    return render(request, 'listdevtype.html', {'objs': devs[s:e], 'pagination': pagination})


@service_required('sys_config')
def add_devtype(request):
    """添加设备类型"""
    if request.POST:
        user = get_user(request)
        devt = DevType()
        devtys = DevType.objects.values_list('name')
        devt.name = request.POST.get('name', '').strip()
        devt.ename = request.POST.get('ename', '').strip()
        devt.identify = request.POST.get('identify', 0)
        for devty in devtys:
            if devt.name in devty:
                return ajaxresponse({'head': 'ERROR', 'body': u'添加设备失败，此设备类型名称已存在'})
        devt.desc = request.POST.get('desc', '').strip()
        devt.useradd = 1
        devt.save()
        savelog(request, 'config', u'系统', u'系统', 6, u'设备类型', u'%s添加设备类型，名称是%s' % (user, devt.name))
        return ajaxresponse({'head': 'OK', 'body': u'添加设备类型成功', 'redirect': '/assetmgnt/listdevtype'})
    else:
        resp = DevEname.objects.filter(is_show=1)
        return render(request, 'adddevtype.html', {"obj": resp})


@service_required('sys_config')
def edit_devtype(request):
    """修改设备类型"""
    if request.POST:
        user = get_user(request)
        id = request.POST.get('id', 0).strip()
        try:
            devt = DevType.objects.get(id=id)
            devt.name = request.POST.get('name', '').strip()
            try:
                res = DevType.objects.filter(name=devt.ename)
                if len(res) == 0:
                    pass
                elif len(res) == 1:
                    if res[0].id == int(id):
                        pass
                    else:
                        return ajaxresponse({'head': 'ERROR', 'body': u'修改设备失败，此设备类型名称已存在'})
                else:
                    return ajaxresponse({'head': 'ERROR', 'body': u'修改设备失败，此设备类型名称已存在'})
            except:
                pass
            devt.identify = request.POST.get('marking', '').strip()
            devt.desc = request.POST.get('desc', '').strip()
            devt.ename = request.POST.get('ename', '').strip()
            devt.save()
            savelog(request, 'config', u'系统', u'系统', 6, u'设备类型', u'%s修改设备类型，被修改设备名称是%s' % (user, devt.name))
        except Exception as e:
            return ajaxresponse({'head': 'ERROR', 'body': u'编辑设备类型失败'})
        return ajaxresponse({'head': 'OK', 'body': u'设备类型编辑成功', 'redirect': '/assetmgnt/listdevtype'})
    else:
        did = request.GET.get('did', '').strip()
        id = Cryption.decrypt(did)
        _id = id.decode('utf-8')
        try:
            devt = DevType.objects.get(id=_id)
            resp = DevEname.objects.filter(is_show=1)
            return render(request, 'editdevtype.html', {'dev': devt, "obj": resp})
        except:
            return render(request, 'inform.html', {'title': 'ERROR', 'message': u'无法获取设备类型'})


@service_required('sys_config')
def del_devtype(request):
    """删除设备"""
    hid = request.GET.get('did', '').strip()
    id = Cryption.decrypt(hid)
    user = get_user(request)
    try:
        if Device.objects.filter(dtype_id=id).exists():
            return ajaxresponse({'head': 'ERROR', 'body': "该类型已有设备引用"})
        devt = DevType.objects.get(id=id)
        savelog(request, 'config', u'系统', u'系统', 6, u'系统配置', u'%s删除设备,被删设备类型为:%s' % (user.username, devt.name))
        devt.delete()
    except Exception as e:
        return ajaxresponse({'head': 'ERROR', 'body': str(e)})
    return ajaxresponse({'head': 'OK', 'body': u'设备类型删除成功'})
